<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/3/12 11:53
 */
//error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
\ns_core\m_load::load_np("np_http_curl.class.php");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{
    /**
     * CDN注入统一解释器入口
     */
    public function explain()
    {
        $fuc_name = (string)$this->get_c2_type();
        if(empty($fuc_name))
        {
            return $this->write_log_return('C2类型参数为空', NS_CDS_FAIL);
        }
        return $this->save_exec_log($this->$fuc_name());
    }


    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $data array(
    'nns_task_type' =>类型,
    'nns_task_id' => 任务ID,
    'nns_task_name' => 任务名称,
    'nns_action' => 行为动作，
    'nns_content' => 注入XML内容
     * );
     * @return array('ret','reason');
     */
    public function execute($data, $media_info = array())
    {
        $data['nns_id'] = $this->get_guid();
        $task = \m_config::write_cdn_import_execute_log($this->str_sp_id,$data['nns_task_type'],$data['nns_action'],$data['nns_content']);
        if($task['ret'] != 0)
        {
            return $task;
        }

        $local_url = $task['data_info']['base_dir'];

        $obj_curl = new np_http_curl_class();

        $arr_header = array(
            "Content-Type: text/xml; charset=utf-8",
            "Content-Length: ".strlen($data['nns_content']),
        );
        $adr_action = isset($data['adr_action']) && strlen($data['adr_action']) > 0 ? $data['adr_action'] : "TransferContent";
        unset($data['adr_action']);
        $post_host = trim($this->arr_sp_config['cdn_send_mode_url'], '/') . '/' . $adr_action;
        $obj_curl->post($post_host, $data['nns_content'],$arr_header,60);
        $curl_info = $obj_curl->curl_getinfo();
        $arr_media = array();
        switch ($curl_info['http_code'])
        {
            case 200:
                if ($adr_action == 'TransferContent')
                {//如果为添加，则状态为等待异步反馈
                    $re_code = NS_CDS_CDN_LOADING;
                    $re_reason = '发送到CDN成功';//发送cdn成功，在播控描述为正在注入，因为要等待cdn异步反馈
                }
                else
                {//若果为删除、取消，则状态为直接成功
                    $re_code = NS_CDS_CDN_SUCCE;
                    $re_reason = '注入成功';
                }
                break;
            case 400:
                $re_code = -1;
                $re_reason = '发送的请求有问题';
                break;
            case 404:
                $re_code = -1;
                $re_reason = '资源没有找到';
                break;
            case 409:
                $re_code = 0;
                $re_reason = 'CDN资源已经存在，注入成功';
                //配置注入数码CDN，内蒙广电分配的providerID
                $str_provider_id = 'nmly';
                //更新片源媒资的播放串地址
                $arr_media = array(
                    'media_where' => array(
                        'nns_import_id' => $media_info['base_info']['cdn_id'],
                        'nns_kbps' => $media_info['base_info']['nns_kbps'],
                    )
                );
                $str_play_url = json_encode(array(
                    'play_url' => '/vod/' . $str_provider_id . '_' . $media_info['base_info']['cdn_id'] . '_' . $media_info['base_info']['nns_kbps'] . '.m3u8',
                ));
                $arr_media['media_filed'] = array(
                    'nns_ext_url' => addslashes($str_play_url),
                );

                break;
            case 500:
                $re_code = -1;
                $re_reason = '服务器内部错误';
                break;
            case 521:
                $re_code = 1;
                $re_reason = '文件下载失败';
                break;
            case 522:
                $re_code = -1;
                $re_reason = '生成文件索引失败';
                break;
            case 523:
                $re_code = -1;
                $re_reason = 'CDN磁盘空间不足';
                break;
            case 524:
                $re_code = -1;
                $re_reason = '没有合适的 CL';
                break;
            default:
                $re_code = -1;
                $re_reason = '发送失败';
        }
        $data['nns_url'] = $local_url;
        $data['nns_result'] = $re_code;
        $data['nns_result_fail_reason'] = $re_reason;
        if ($re_code != NS_CDS_CDN_NOTIFY_SUCCE || $adr_action != 'TransferContent')
        {
            $data['nns_notify_result'] = $re_code;
            $data['nns_notify_time'] = date("Y-m-d H:i:s");
            $data['nns_notify_fail_reason'] = $re_reason;
        }

        $data['nns_send_time'] = date("Y-m-d H:i:s");
        $data['nns_task_id'] = $this->get_c2_info('id');
        $data['nns_task_name'] = $this->get_c2_info('name');

        /**
         * $data
         * array(
         *            'nns_task_type'=>'Series',
         *            'nns_task_id'=> 'C2任務ID',
         *            'nns_task_name'=> '任務名稱',
         *            'nns_action'=> '行為動作',
         *            'nns_result' => 0 成功 其他失敗
         *            'nns_result_fail_reason' => 發送失敗原因描述
         *      )
         * */
        $build_c2 = $this->build_c2_log($data);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }
        //资源存在的话，当作异步反馈处理，反馈直接存在
        if ($re_code == NS_CDS_CDN_NOTIFY_SUCCE && $adr_action == 'TransferContent')
        {
            return $this->notify($arr_media, $re_code, $re_reason);
        }
        return $this->is_ok($re_code, $re_reason);
    }

    /**
     * 异步反馈
     * @param $arr_media
     * @param $code
     * @param $reason
     * @return array
     */
    public function notify($arr_media, $code, $reason)
    {
        $re_media = $this->get_media_info_by_condition($arr_media['media_where']);
        if ($re_media['ret'] != 0)
        {
            return $this->write_log_return($re_media['reason'], $re_media['ret']);
        }

        if (isset($arr_media['media_filed']) && is_array($arr_media['media_filed']) && count($arr_media['media_filed']) > 0)
        {
            $ed_media = $this->edit_media_info($arr_media['media_filed'], $re_media['data_info'][0]['nns_id']);
            if ($ed_media['ret'] != 0)
            {
                return $this->write_log_return($ed_media['reason'], $ed_media['ret']);
            }
        }

        $arr_c2_task = array(
            'nns_ref_id' => $re_media['data_info'][0]['nns_id'],
            'nns_type' => 'media',
        );

        return $this->is_notify_ok_v2($arr_c2_task, $code, $reason);
    }

    private function video()
    {
        return m_config::return_data(1,'不注入主媒资信息');
    }

    private function index()
    {
        return m_config::return_data(1,'不注入分集信息');
    }


    private function media()
    {
        if ($this->get_c2_info("action") === 'destroy')
        {
            return $this->do_destroy( 'DELETE', 'media');
        }
        else
        {
            $action = 'REGIST';
        }

        //获取config_v2配置文件，播控v2版，数码cdn反馈地址
        $bk_web_url = get_config_v2("g_bk_v2_notify_url");
        $bk_web_url = trim(trim(trim($bk_web_url,'\\'),'/'));
        $bk_project = \evn::get('project');
        $bk_web_url.="/v2/ns_api/{$bk_project}/delivery/{$this->str_sp_id}/notify.php";

        $media_info = $this->get_media_info();
        if (empty($media_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }

        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("主媒资C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }

        if(isset($this->arr_sp_config['disabled_clip']) && (int)$this->arr_sp_config['disabled_clip'] !== 2 && (int)$this->arr_sp_config['disabled_clip'] !== 3)
        {
            $file_path = $this->get_c2_info("file_path");
            $media_info['base_info']['nns_url'] = ltrim((trim($file_path)),'/');
            if(isset($this->arr_sp_config['media_ftp']) && !empty($this->arr_sp_config['media_ftp']))
            {
                $this->arr_sp_config['media_ftp'] = rtrim((trim($this->arr_sp_config['media_ftp'])),'/');
                if (stripos($media_info['base_info']['nns_url'], 'http://') === FALSE && stripos($media_info['base_info']['nns_url'], 'ftp://') === FALSE)
                {
                    $media_info['base_info']['nns_url'] = $this->arr_sp_config['media_ftp'].'/'.$media_info['base_info']['nns_url'];
                }
            }
        }
        else
        {
            $media_info['base_info']['nns_url'] = ltrim((trim($media_info['base_info']['nns_url'])),'/');
            if(isset($this->arr_sp_config['media_ftp']) && !empty($this->arr_sp_config['media_ftp']))
            {
                $this->arr_sp_config['media_ftp'] = rtrim((trim($this->arr_sp_config['media_ftp'])),'/');
                if (stripos($media_info['base_info']['nns_url'], 'http://') === FALSE && stripos($media_info['base_info']['nns_url'], 'ftp://') === FALSE)
                {
                    $media_info['base_info']['nns_url'] = $this->arr_sp_config['media_ftp'].'/'.$media_info['base_info']['nns_url'];
                }
            }
        }

        $arr_parse_url = parse_url($media_info['base_info']['nns_url']);
        $temp_url = '';
        $temp_username = (isset($arr_parse_url['user']) && strlen($arr_parse_url['user']) >0) ? $arr_parse_url['user'] : '';
        $temp_password = (isset($arr_parse_url['pass']) && strlen($arr_parse_url['pass']) >0) ? $arr_parse_url['pass'] : '';
        if(isset($arr_parse_url['scheme']) && strlen($arr_parse_url['scheme'])>0)
        {
            $temp_url.=$arr_parse_url['scheme']."://";
        }
        if(isset($arr_parse_url['host']) && strlen($arr_parse_url['host'])>0)
        {
            $temp_url.=$arr_parse_url['host'];
        }
        if(isset($arr_parse_url['port']) && strlen($arr_parse_url['port'])>0)
        {
            $temp_url.=":".$arr_parse_url['port'];
        }
        if(isset($arr_parse_url['path']) && strlen($arr_parse_url['path'])>0)
        {
            $temp_url.=$arr_parse_url['path'];
        }
        if(isset($arr_parse_url['query']) && strlen($arr_parse_url['query'])>0)
        {
            $temp_url.='?'.$arr_parse_url['query'];
        }

        $xml_str = '<?xml version="1.0" encoding="utf-8"?>';
        $xml_str.= '<TransferContent ';
        $xml_str.=     'providerID="nmly" ';
        $xml_str.=     'assetID="'.$cdn_import_id.'" ';
        $xml_str.=     'transferBitRate="'.$media_info['base_info']['nns_kbps'].'" ';
        $xml_str.=     'volumeName="nmly" ';
        $xml_str.=     'responseURL="'.$bk_web_url.'" ';
        $xml_str.=     'startNext="false" ';
        $xml_str.= '>';
        $xml_str.=     '<Input ';
        $xml_str.=         'subID="'.$media_info['base_info']['nns_kbps'].'" ';
        $xml_str.=         'format ="'.$media_info['base_info']['nns_filetype'].'" ';
        $xml_str.=         'sourceURL="'.$temp_url.'" ';
        $xml_str.=         'userName="'.$temp_username.'" ';
        $xml_str.=         'password="'.$temp_password.'" ';
        $xml_str.=         'serviceType="2" ';
        $xml_str.=      '/>';
        $xml_str.= '</TransferContent>';
        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' =>'Movie',
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
            'adr_action' => "TransferContent",//请求数码的方法
        );
        $media_info['base_info']['cdn_id'] = $cdn_import_id;
        return $this->execute($execute_info, $media_info);
    }

    /**
     * 主媒资、分集、片源的删除
     * @param string $action
     * @param string $video_type
     * @return array
     */
    private function do_destroy($action='', $video_type = "media")
    {
        if (!isset($action) && $this->get_c2_info("action") === NS_CDS_DELETE)
        {
            $action = "DELETE";
        }
        $action = isset($action) && strlen($action) > 0 ? strtoupper($action) : "DELETE";

        /*******获取CDN注入ID******/
        $cdn_import_id = $this->get_video_cdn_import_id($video_type);
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("C2任务生成CDN注入ID失败", NS_CDS_FAIL);
        }

        $media_info = $this->get_media_info();
        if (empty($media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }

        //映射节点类型
        switch ($video_type)
        {
            case "video" :
                $type = "Series";
                break;
            case "index" :
                $type = "Program";
                break;
            case "media" :
                $type = "Movie";
                break;
            default :
                $type = "Series";
                break;
        }

        $xml_str = '<?xml version="1.0" encoding="utf-8"?>';
        $xml_str.= '<DeleteContent ';
        $xml_str.=     'providerID="nmly" ';
        $xml_str.=     'assetID="'.$cdn_import_id.'" ';
        $xml_str.=     'volumeName="nmly" ';
        $xml_str.=     'reasonCode="200" ';
        $xml_str.= '>';
        $xml_str.=     '<Input ';
        $xml_str.=         'subID="'.$media_info['base_info']['nns_kbps'].'" ';
        $xml_str.=         'format="ts" ';
        $xml_str.=         'serviceType="2" ';
        $xml_str.=      '/>';
        $xml_str.= '</DeleteContent>';

        /*******调用统一注入方法******/
        $execute_info = array(
            'nns_task_type' => $type,//删除操作的媒资类型，主媒资、分集、片源
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
            'nns_action' => $action, //行为动作
            'nns_content' => $xml_str,//注入XML内容
            'adr_action' => "DeleteContent",//请求数码的方法
        );
        return $this->execute($execute_info);
    }

}